#!/bin/bash
# Gitee 专用内核构建脚本

set -e

echo "🔨 Gitee 专用内核构建"

# 检测环境
source scripts/gitee/detect-environment.sh

# 设置镜像源
bash scripts/gitee/setup-mirrors.sh

# 显示构建信息
echo "📋 构建配置:"
echo "  - 设备: $1"
echo "  - 架构: arm64"
echo "  - 工具链: aarch64-linux-gnu"
echo "  - 环境: $([ "$IS_GITEE_CI" = "true" ] && echo "Gitee CI" || echo "本地")"

DEVICE=${1:-"mondrian"}

# 验证设备
case $DEVICE in
    "mondrian"|"vermeer"|"sheng")
        ;;
    *)
        echo "❌ 错误: 不支持的设备 $DEVICE"
        echo "支持的设备: mondrian, vermeer, sheng"
        exit 1
        ;;
esac

# 下载工具链
echo "📥 准备工具链..."
bash scripts/gitee/download-toolchains.sh

# 设置环境变量
export ARCH=arm64
export CROSS_COMPILE=aarch64-linux-gnu-
export CCACHE_DIR="$PWD/.ccache"

# 创建输出目录
mkdir -p out/$DEVICE

# 配置内核
echo "⚙️ 配置内核 ($DEVICE)..."
if [ ! -f "arch/arm64/configs/${DEVICE}_defconfig" ]; then
    echo "❌ 错误: 配置文件 arch/arm64/configs/${DEVICE}_defconfig 不存在"
    exit 1
fi

make O=out/$DEVICE ${DEVICE}_defconfig

# 构建内核
echo "🚀 开始编译..."
make -j$(nproc) O=out/$DEVICE CROSS_COMPILE=aarch64-linux-gnu-

# 验证构建结果
echo "🔍 验证构建结果..."
if [ -f "out/$DEVICE/arch/arm64/boot/Image.gz-dtb" ]; then
    echo "✅ 内核镜像: out/$DEVICE/arch/arm64/boot/Image.gz-dtb"
    ls -lh "out/$DEVICE/arch/arm64/boot/Image.gz-dtb"
elif [ -f "out/$DEVICE/arch/arm64/boot/Image" ]; then
    echo "✅ 内核镜像: out/$DEVICE/arch/arm64/boot/Image"
    ls -lh "out/$DEVICE/arch/arm64/boot/Image"
else
    echo "❌ 错误: 内核镜像未找到"
    ls -la "out/$DEVICE/arch/arm64/boot/"
    exit 1
fi

echo "🎉 $DEVICE 内核构建成功!"
